package com.example.vaccine.mapper;

import com.example.vaccine.entity.CheckTasks;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author Coisn
 * @since 2025-06-12
 */
@Mapper
public interface CheckTasksMapper extends BaseMapper<CheckTasks> {

    @Select("SELECT vaccine_numbering FROM check_tasks WHERE status IN ('assigned', 'in_progress')")
    List<String> selectAssignedVaccineNumberings();


    @Select({
            "<script>",
            "SELECT status, COUNT(*) AS count FROM check_tasks",
            "<if test='startTime != null'> WHERE assigned_at &gt;= #{startTime} </if>",
            "GROUP BY status",
            "</script>"
    })
    List<Map<String, Object>> selectStatusCountRaw(@Param("startTime") LocalDateTime startTime);

    default Map<String, Integer> countStatusAfter(LocalDateTime startTime) {
        List<Map<String, Object>> list = selectStatusCountRaw(startTime);

        Map<String, Integer> map = new HashMap<>();
        map.put("未开始", 0);
        map.put("进行中", 0);
        map.put("已完成", 0);

        // 状态映射（根据数据库实际返回字段修改）
        Map<String, String> statusMap = new HashMap<>();
        statusMap.put("pending", "未开始");
        statusMap.put("in_progress", "进行中");
        statusMap.put("completed", "已完成");
        // 若数据库直接返回中文，则可省略 statusMap

        for (Map<String, Object> item : list) {
            String rawStatus = (String) item.get("status");
            Integer count = ((Number) item.get("count")).intValue();

            String mappedStatus = statusMap.getOrDefault(rawStatus, rawStatus);
            if (map.containsKey(mappedStatus)) {
                map.put(mappedStatus, count);
            }
        }
        return map;
    }

}
